//
//  ExtensionImage.swift
//  StoreManage
//
//  Created by MC on 2017/12/18.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

extension UIImage {
    
    // 给图片添加水印图片
    func MCImage_addWatermark(image:UIImage,scale:CGFloat) -> UIImage {
        UIGraphicsBeginImageContext(self.size)
        
        self.draw(in: CGRect.init(x: 0, y: 0, width: self.size.width, height: self.size.height))
        
        let waterWH = self.size.width / scale
        let waterX = (self.size.width - waterWH) / 2
        let waterH = (self.size.height - waterWH) / 2
        
        image.draw(in: CGRect.init(x: waterX, y: waterH, width: waterWH, height: waterWH))
        UIGraphicsEndPDFContext()
        let imageNew = UIGraphicsGetImageFromCurrentImageContext()
        return imageNew!
    }
    
    
    /**
     *  压缩上传图片到指定字节
     *
     *  image     压缩的图片
     *  maxLength 压缩后最大字节大小
     *
     *  return 压缩后图片的二进制
     */
    func MCImage_compressImage(maxLength: Int) -> UIImage {
        
        let newSize = self.MCImage_getImageSize(imageMaxLength: 300)
        let newImage = self.MCImage_resize(newSize: newSize)
        
        var compress:CGFloat = 0.9
        var data = UIImageJPEGRepresentation(newImage, compress)
        
        while (data?.count)! > maxLength && compress > 0.01 {
            compress -= 0.02
            data = UIImageJPEGRepresentation(newImage, compress)
        }
        let image = UIImage.init(data: data!) ?? UIImage()        
        return image
    }
    
    
    /**
     *  获得指定size的图片
     *
     *  image   原始图片
     *  newSize 指定的size
     *
     *  return 调整后的图片
     */
    func MCImage_resize(newSize: CGSize) -> UIImage {
        UIGraphicsBeginImageContext(newSize)
        self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? UIImage()
    }
    
    /**
     *  通过指定图片最长边，获得等比例的图片size
     *
     *  image       原始图片
     *  imageLength 图片允许的最长宽度（高度）
     *
     *  return 获得等比例的size
     */
    func MCImage_getImageSize(imageMaxLength: CGFloat) -> CGSize {
        
        var newWidth:CGFloat = 0.0
        var newHeight:CGFloat = 0.0
        let width = self.size.width
        let height = self.size.height
        
        if (width > imageMaxLength || height > imageMaxLength){
            
            if (width > height) {
                newWidth = imageMaxLength;
                newHeight = newWidth * height / width;
            }else if(height > width){
                newHeight = imageMaxLength;
                newWidth = newHeight * width / height;
            }else{
                newWidth = imageMaxLength;
                newHeight = imageMaxLength;
            }
        }
        return CGSize(width: newWidth, height: newHeight)
    }
    

    


    
    
    /// 更改图片颜色
    func MCImageWithTintMainColor() -> UIImage {
        return MCImageWithTintColor(color: UIColor.MCMain)
    }
    
    public func MCImageWithTintColor(color : UIColor) -> UIImage{
        let drawRect = CGRect.init(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        
        color.setFill()
        UIRectFill(drawRect)
        draw(in: drawRect, blendMode: CGBlendMode.destinationIn, alpha: 1.0)
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return tintedImage!
    }
    
    
    // 通过rect，裁切图片
    func MCImageCrop(toRect:CGRect) -> UIImage {

        let imageRef = self.cgImage?.cropping(to: toRect)
        let image = UIImage.init(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation)
        
        return image
    }
}




// 将一个视图转为图片
func MCImage_createdWithView(view : UIView) -> UIImage {
    let size = view.bounds.size
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了
    UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}


// 通过颜色生成图片
func MCImage_createdFormColor(color : UIColor) -> UIImage {
    let rect = CGRect.init(x: 0.0, y: 0.0, width: 6.0, height: 6.0)
    UIGraphicsBeginImageContext(rect.size)
    let context : CGContext = UIGraphicsGetCurrentContext()!
    context.setFillColor(color.cgColor)
    context.fill(rect)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

// 获取网络图片
func MCImage_createFromURL(fileURL:String) -> UIImage? {
    if fileURL.count == 0 {
        return nil
    }
    let data = NSData.init(contentsOf: URL.init(string: fileURL)!)
    
    if data == nil {
        return nil
    }
    
    return UIImage.init(data: data! as Data)!
}


// 生成二维码图片
func MCImage_createQRForString(qrString: String?, iconImage: UIImage?) -> UIImage? {
    
    if let sureQRString = qrString {
        let stringData = sureQRString.data(using: String.Encoding.utf8, allowLossyConversion: false)
        //创建一个二维码的滤镜
        let qrFilter = CIFilter(name: "CIQRCodeGenerator")
        qrFilter?.setValue(stringData, forKey: "inputMessage")
        qrFilter?.setValue("H", forKey: "inputCorrectionLevel")
        let qrCIImage = qrFilter?.outputImage
        
        // 创建一个颜色滤镜,黑白色
        let colorFilter = CIFilter(name: "CIFalseColor")!
        colorFilter.setDefaults()
        colorFilter.setValue(qrCIImage, forKey: "inputImage")
        colorFilter.setValue(CIColor(red: 0, green: 0, blue: 0), forKey: "inputColor0")
        colorFilter.setValue(CIColor(red: 1, green: 1, blue: 1), forKey: "inputColor1")
        // 返回二维码image
        let codeImage = UIImage(ciImage: (colorFilter.outputImage!.transformed(by: CGAffineTransform(scaleX: 5, y: 5))))
        
        // 中间一般放logo
        if iconImage != nil {
            let whiteImage = MCImage_createdFormColor(color: UIColor.white)
            let whiteWaterImage = codeImage.MCImage_addWatermark(image: whiteImage, scale: 4.1)
            let waterImage = whiteWaterImage.MCImage_addWatermark(image: iconImage!, scale: 5)
            return waterImage
        }
        return codeImage
    }
    return nil
}



